import mysql.connector
from mysql.connector import Error

def create_database():
    connection = None
    try:
        # 连接到MySQL服务器（不指定数据库）
        connection = mysql.connector.connect(
            host='ip',
            port=port,
            user='user',
            password='password'
        )
        
        if connection.is_connected():
            cursor = connection.cursor()
            # 创建数据库
            cursor.execute("CREATE DATABASE IF NOT EXISTS erp_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
            print("数据库 'erp_db' 创建成功或已存在")
            
            # 使用数据库
            cursor.execute("USE erp_db")
            
            # 创建用户表
            create_users_table = """
            CREATE TABLE IF NOT EXISTS users (
                id INT AUTO_INCREMENT PRIMARY KEY,
                username VARCHAR(80) UNIQUE NOT NULL,
                email VARCHAR(120) UNIQUE NOT NULL,
                password_hash VARCHAR(255) NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            """
            cursor.execute(create_users_table)
            print("用户表创建成功")
            
    except Error as e:
        print(f"创建数据库时出错: {e}")
        
    finally:
        if connection and connection.is_connected():
            cursor.close()
            connection.close()
            print("MySQL连接已关闭")

if __name__ == "__main__":
    create_database()